package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.entity.HouseImage;
import com.atguigu.result.Result;
import com.atguigu.service.HouseImageService;
import com.atguigu.util.QiniuUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * @PACKAGE_NAME: com.atguigu.controller
 * @CLASSNAME: HouseImageController
 * @AUTHOR: zhangsan
 * @DATE: 2024/4/24 19:31
 * @SINCE 17.0.7
 * @DESCRIPTION: HouseImageController
 */
@Slf4j
@Controller
@RequestMapping("/houseImage")
public class HouseImageController {
    /**
     * 页面
     */
    private static final String PAGE_UPLOAD = "house/upload";
    private static final String LIST_ACTION = "redirect:/house/";
    private static final String PAGE_SUCCESS = "common/successPage";
    /**
     * 七牛云外链
     */
    private static final String houseDomainName = "http://scfvqarb1.hb-bkt.clouddn.com/";
    /**
     * 上传到指定文件夹house/下
     */
    public static String directory = "house/";
    @Reference
    private HouseImageService houseImageService;

    @RequestMapping("/uploadShow/{houseId}/{type}")
    public String toUploadPage(@PathVariable("houseId") Long houseId,
                               @PathVariable("type") Integer type,
                               Model model) {
        model.addAttribute("houseId", houseId);
        model.addAttribute("type", type);
        return PAGE_UPLOAD;
    }

    /**
     * 83178
     * ------WebKitFormBoundarywWahU6253YZoUmMi
     * Content-Disposition: form-data; name="file"; filename="pc0_Luqouk0Gt.jpg"
     * Content-Type: image/jpeg
     *
     * @param houseId
     * @param type
     * @param files
     * @return
     */
    @RequestMapping("/upload/{houseId}/{type}")
    @ResponseBody
    public Result upload2Qiniu(@PathVariable("houseId") Long houseId,
                               @PathVariable("type") Integer type,
                               @RequestParam("file") MultipartFile[] files) {
        //发送请求失败,没有收到要上传的文件
        if (files == null || files.length == 0) {
            return Result.fail();
        }

        try {
            for (MultipartFile file : files) {
                String fileName = UUID.randomUUID().toString();
                String key = directory+fileName;
                String retKey = QiniuUtil.upload2Qiniu(file.getBytes(), key);
                //文件上传失败
                if (retKey == null || retKey.isEmpty()) {
                    return Result.fail();
                }
                String imageUrl = houseDomainName + key;
                //文件上传成功,将文件地址写入到数据库中
                HouseImage houseImage = new HouseImage();
                houseImage.setId(null);
                houseImage.setHouseId(houseId);
                houseImage.setImageName(file.getOriginalFilename());
                houseImage.setImageUrl(imageUrl);
                houseImage.setType(type);
                Integer i = houseImageService.insert(houseImage);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return Result.ok();
    }

    @RequestMapping("/delete/{houseId}/{id}")
    public String deleteImage(@PathVariable("houseId") Long houseId,
                              @PathVariable("id") Long id) {
        //先删除七牛云,再删除数据库
        HouseImage houseImage = houseImageService.getById(id);
        String imageUrl = houseImage.getImageUrl();
        Boolean exists = QiniuUtil.existsByUrl(imageUrl);
        if (exists) {
            //如果七牛云中存在则先从七牛云删除,再从数据库删除
            Boolean b = QiniuUtil.deleteFileFromQiniuByUrl(imageUrl);
            if (b) {
                Integer delete = houseImageService.delete(id);
            }
        } else {
            //如果七牛云中不存在,则直接从数据库删除
            Integer delete = houseImageService.delete(id);
        }
        return LIST_ACTION + houseId;
    }
}
